package com.stsmobile;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Search extends ListActivity{
	private static final CharSequence ERROR_MESSAGE = "Unable to connect\n" +
			"to the STS database.";

	@Override
	public void onResume(){
		super.onResume();
		if(STSApplication.loggingOut()){
			finish();
		}
		if(STSApplication.toHome()){
			finish();
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		ArrayList<String> shipments = new ArrayList<String>();
		shipments = STSApplication.getShipmentList();
		String[] finalshipments = new String[shipments.size()];
		int count = 0;
		for(String s: shipments){
			finalshipments[count] = s;
			count++;
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, finalshipments);
		setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		String item = (String) getListAdapter().getItem(position);
		findShipment(item);
	}
	
	private void findShipment(String shipment_id) {
		String result = STSApplication.retrieveShipment(shipment_id);

		if(result.contains("<success>"))
		{
			Intent nextpage = new Intent("com.stsmobile.ShipmentHome");
			startActivity(nextpage);
		}else
		{
			CharSequence errorMessage="";
			
			//Get error message from server's response.
			int startMessage = result.indexOf("<msg>")+5;
			int endMessage = result.indexOf("</msg>");
			
			if(startMessage!=-1 && endMessage!=-1)
				errorMessage = result.substring(startMessage,endMessage);
				
			if(errorMessage.equals(""))
				errorMessage=ERROR_MESSAGE;
			
			//Display Error Message to User in a Popup
			Context cur_context = getApplicationContext();
			int duration = Toast.LENGTH_LONG;
			Toast displaymessage = Toast.makeText(cur_context, errorMessage, duration);
			displaymessage.show();
		}
	}
}
